{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CSE 160: Worksheet 1 - Loops & Range - Solutions\n", "\n", "Please try to answer the following questions without running any code initially.\n", "\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Problem 1**\n", "\n", "How many times will the following loops iterate?\n", "\n", "```\n", "for i in range(7):\n", " \n", " \n", "for i in [1,2,3,4,5]:\n", " \n", " \n", "for i in range(0,4):\n", " \n", " \n", "for i in range(5, 1, -1):\n", " \n", "```\n", "\n", "***" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n", "5\n", "4\n", "4\n" ] } ], "source": [ "n = 0\n", "for i in range(7):\n", " n=n+1\n", "print(n)\n", "\n", "#--------------------\n", "n = 0\n", "for i in [1,2,3,4,5]:\n", " n=n+1\n", "print(n)\n", "\n", "#--------------------\n", "n = 0\n", "for i in range(0,4):\n", " n=n+1\n", "print(n)\n", "\n", "#--------------------\n", "n = 0\n", "for i in range(5, 1, -1):\n", " n=n+1\n", "print(n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Problem 2**\n", "\n", "What is the expected code for the following loops?\n", "\n", "```\n", "for letter in \"data is fun\":\n", " print(letter + \"~\", end=\"\") # end=\"\" suppresses the automatic new line\n", "```\n", " " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "d~a~t~a~ ~i~s~ ~f~u~n~" ] } ], "source": [ "for letter in \"data is fun\":\n", " print(letter + \"~\", end=\"\") " ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 2 \n", "5 7 9 11 13 \n", "10 9 8 7 6 5 4 3 2 \n" ] } ], "source": [ "for i in range(3):\n", " print(i, end=\" \")\n", "print()\n", " \n", "#--------------------\n", "for j in range(5,15,2):\n", " print(j, end=\" \")\n", "print()\n", " \n", "#--------------------\n", "for k in range(10,1,-1):\n", " print(k, end=\" \")\n", "print()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.1" } }, "nbformat": 4, "nbformat_minor": 2 }